﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：开关
    /// </summary>
    public class ec_CircuitBreakerService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_CircuitBreakerEntity> _circuitBreakerRepository => new Repository<ec_CircuitBreakerEntity>();
        #endregion
        #region 获取数据


        /// <summary>
        /// 获取列表数据(开关表+PDBNAME+OBJECTTYPENAME)
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_CircuitBreakerEntity> GetList(string queryJson)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                //参考写法
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(@"SELECT t.*,t4.EngineDataID PDBId,t4.TagNumber PDBName,t3.ObjectTypeName ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    return null;
                }
                else
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($" FROM ec_circuitbreaker_{ProjectEntity.ProjectIndex} t ");
                    strSql.Append($" join ec_enginedata_{ProjectEntity.ProjectIndex} t4 on t4.EngineDataID=t.PDBID ");
                    strSql.Append($" join ec_objecttype_{ProjectEntity.ProjectIndex} t3 on t3.ObjectTypeID=t4.ObjectTypeID ");
                }
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();

                if (!queryParam["EngineerDataID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("EngineerDataID", queryParam["EngineerDataID"].ToString(), DbType.String));
                    strSql.Append(" AND t.EngineerDataID = @EngineerDataID ");
                }
                if (!queryParam["PDBID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("PDBID", queryParam["PDBID"].ToString(), DbType.String));
                    strSql.Append(" AND t.PDBID = @PDBID ");
                }
                if (queryParam["EngineerDataIDs"] != null)
                {
                    if (!queryParam["EngineerDataIDs"].IsEmpty())
                    {
                        //逗号分开的一个字符串
                        string tagNumbers = queryParam["EngineerDataIDs"].ToString();
                        strSql.Append($" AND FIND_IN_SET(t.EngineerDataID, '{tagNumbers}') ");
                    }
                    else
                    {
                        return new List<ec_CircuitBreakerEntity>();
                    }
                }

                //return this.BaseRepository().FindList<ec_CircuitBreakerEntity>(strSql.ToString(), dp);
                return SqlSugarHelper.Db.SqlQueryable<ec_CircuitBreakerEntity>(strSql.ToString()).AddParameters(dp).ToList();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        #endregion

        #region 提交数据
        public void Delete(string ProjectId, string keyValue)
        {
            //var db = this.BaseRepository().BeginTrans();
            _circuitBreakerRepository.AsTenant().BeginTran();
            try
            {
                //关联类型删除时，删除工程数据关联表记录。
                if (string.IsNullOrWhiteSpace(ProjectId))
                {

                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    //db.ExecuteBySql($@" DELETE FROM ec_circuitbreaker_{ProjectEntity.ProjectIndex} WHERE EngineerDataId ='{keyValue}'; ");
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_circuitbreaker_{ProjectEntity.ProjectIndex} WHERE EngineerDataId ='{keyValue}'; ");
                }
                //db.Commit();
                _circuitBreakerRepository.AsTenant().CommitTran();
            }
            catch (Exception ex)
            {
                _circuitBreakerRepository.AsTenant().RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, ref string keyValue, ec_CircuitBreakerEntity entity)
        {
            try
            {
                var ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    //ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(ProjectId);
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }
                else
                {
                    return;
                }

                if (!string.IsNullOrEmpty(keyValue))
                {

                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Update(entity);
                        _circuitBreakerRepository.Update(entity);
                    }
                    else
                    {
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_circuitbreaker_{ProjectEntity.ProjectIndex}", "EngineerDataID");
                        _circuitBreakerRepository.AsUpdateable(entity).AS($"ec_circuitbreaker_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }


                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        //this.BaseRepository().Insert(entity);
                        _circuitBreakerRepository.Insert(entity);
                    }
                    else
                    {
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_circuitbreaker_{ProjectEntity.ProjectIndex}");
                        _circuitBreakerRepository.AsInsertable(entity).AS($"ec_circuitbreaker_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                    keyValue = entity.EngineerDataID;
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
